package com.zmn.oms.third.taobao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.third.taobao.dto.TmcOrderDTO;
import com.zmn.oms.third.taobao.dto.TmcOrderDetailDTO;
import com.zmn.oms.third.taobao.dto.api.TmallApiInvokResult;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类描述：
 *
 * @author LiangHailong
 * @date 2019/06/15 17:40
 */
//@Component("taobaoMessageHandler")
public class TaobaoMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(TaobaoMessageHandler.class);



    @Autowired
    ZsOrderWorkQueryBService zsOrderWorkQueryBService;




    /**
     * 主动拉取并保存指定淘宝订单（用于消息丢失的订单，补充保存）
     * @param outerId
     */
    public void saveOrderByOuterId(Long outerId) {
        logger.info("【{}】主动拉取订单 OuterId:[{}]", TaobaoTmcConstants.NAME_TMALL, outerId);
        try {
            // 查淘宝订单
            TmallApiInvokResult result = TmallApiInvoker.queryOrderDetail(outerId);
            if (!result.isSuccess()) {
                logger.info("【{}】主动拉取订单失败:[{}]", TaobaoTmcConstants.NAME_TMALL, result.getMsg());
                return;
            }
            // 返回格式：
            /* 返回格式：
                {"tmall_servicecenter_task_get_response":{
                    "service_task_packet":{
                        "desc":"Task[parent_biz_order_id=523534752786357574, buyer_id=null] list size: 1",
                        "name":"TaskList",
                        "service_list":{
                            "service_task_d_o":[
                                {
                                    "attribute":";processBizIdentify:523534752786357574;serviceDate:1562724000000;bizOderType:1;serviceStoreTaskType:3;",
                                    "auction_id":579832485379,"auction_name":"家电清洗-热水器清洗服务 家庭家电清洗上门到家服务","auction_price":7900,"biz_order_id":523534752786357574,"buy_amount":1,"buyer_address":"新疆维吾尔自治区乌鲁木齐市天山区天山公园","buyer_location":650102002,"buyer_name":"杨俊全","buyer_phone":"15135165098","expect_date":"2019-07-10 10:00:00","expect_date_number":1562724000000,"gmt_create":"2019-07-10 11:55:37","gmt_modify":"2019-07-10 11:55:37","id":137219062,"parent_biz_order_id":523534752786357574,"seller_id":3885826257,"seller_nick":"天猫无忧购旗舰店","service_count":1,"service_name":"appliance_cleaning","service_order_id":523534752786357574,"task_status":8,"task_type":1,"tp_id":2563261712,"tp_name":"啄木鸟修家电"
                                }
                            ]
                        }
                    },
                    "request_id":"4pdrdghobdpa"
                }}

             */
            JSONObject jsonObject = JSON.parseObject(result.getMsg());
            jsonObject = jsonObject.getJSONObject("tmall_servicecenter_task_get_response");
            jsonObject = jsonObject.getJSONObject("service_task_packet");
            jsonObject = jsonObject.getJSONObject("service_list");

            List<TmcOrderDetailDTO> serviceList = jsonObject.getObject("service_task_d_o",
                    new TypeReference<List<TmcOrderDetailDTO>>() {});

            TmcOrderDTO tmcOrderDTO = BeanMapper.map(serviceList.get(0), TmcOrderDTO.class);

            // 拉取数据中没有ServiceCode字段，改用ServiceName字段，需要做一次转换
            tmcOrderDTO.setServiceCode(tmcOrderDTO.getServiceName());
            // 预约时间已过，重设预约时间
            String expectDate = tmcOrderDTO.getExpectDate();
            if (StringUtils.isNotBlank(expectDate) && DateUtil.parse(expectDate).getTime() <= System.currentTimeMillis()) {
                tmcOrderDTO.setExpectDate(null);
            }

            /*
            CreateOrderDTO createOrderDTO = buildOrderDTO(tmcOrderDTO);

            if (createOrderDTO != null) {
                String outerData = String.format("{\"result\":%s}", JSON.toJSON(tmcOrderDTO));
                createOrderDTO.setOuterData(outerData);

                OrderBO orderBO = proxyOrderBService.createOrder(createOrderDTO);
                logger.info("【{}】主动拉取订单成功 OrderId:[{}]", TaobaoTmcConstants.NAME_TMALL_WYG, orderBO.getOrder().getOrderId());
            }
            */
        } catch (Exception e) {
            logger.info("【{}】主动拉取订单失败 OuterId:[{}]", TaobaoTmcConstants.NAME_TMALL, outerId);
            logger.error(e.getMessage(), e);
        }
    }


    public static void main(String[] args) {
        String token = "6201905d630d0ZZ7c9896520a671383962985ad41f9dd822563261712";
        TaobaoTmcConstants.APPKEY = "27577705";
        TaobaoTmcConstants.SECRET = "7b71e52d7a0cb8d20defff143e74a6f7";
        //TaobaoTmcConstants.API_URL = "http://140.205.164.4/top/router/rest";
        TaobaoTmcConstants.API_URL = "http://gw.api.taobao.com/router/rest";
        // 查淘宝订单
        TmallApiInvokResult result = TmallApiInvoker.queryOrderDetail(749210787893430850L, token);
        if (!result.isSuccess()) {
            logger.info("【{}】主动拉取订单失败:[{}]", TaobaoTmcConstants.NAME_TMALL, result.getMsg());
            return;
        }

        JSONObject jsonObject = JSON.parseObject(result.getMsg());
        jsonObject = jsonObject.getJSONObject("tmall_servicecenter_task_get_response");
        jsonObject = jsonObject.getJSONObject("service_task_packet");
        jsonObject = jsonObject.getJSONObject("service_list");
        List<TmcOrderDetailDTO> serviceList = jsonObject.getObject("service_task_d_o", new TypeReference<List<TmcOrderDetailDTO>>() {
        });
        TmcOrderDTO tmcOrderDTO = BeanMapper.map(serviceList.get(0), TmcOrderDTO.class);
        String attribute = serviceList.get(0).getAttribute();
        if (StringUtils.isNotBlank(attribute)) {
            String[] strArray = attribute.split(";");
            List list = Arrays.asList(strArray);
            Map<String, String> attributeMap = new HashMap();
            list.forEach((item) -> {
                if (StringUtils.isNotBlank(item.toString())) {
                    String[] attributes = item.toString().split(":");
                    System.out.println(attributes.length);
                    if (attributes.length == 2) {
                        attributeMap.put(attributes[0], attributes[1]);
                    }
                }
            });
            tmcOrderDTO.setAttributes(attributeMap);
        }

        System.out.println(JSON.toJSON(tmcOrderDTO));
    }
}
